import httpx

# 回调函数：处理 注册POST 请求的响应
def handle_post_response_register(response: httpx.Response):
    global groupId, clientId, uname, pwd
    print(response)
    if response.status_code == 200:
        data = response.json()
        groupId = data["Result"]["groupId"]
        clientId = data["Result"]["clientId"]
        uname = data["Result"]["uname"]
        pwd = data["Result"]["pwd"]
        print("POST 请求返回的数据：")
        print(data)
    else:
        print(f"POST 请求失败，状态码：{response.status_code}")
    return groupId, clientId, uname, pwd
# 回调函数：处理授权POST 请求的响应
def handle_post_response_authorize(response: httpx.Response):
    global eew_topic, eqr_topic, ack_topic, mqtthost,port,scopeLast
    if response.status_code == 200:
        data = response.json()
        results = data["Result"]
        if results :
            for result in results:
                if result['scope'] == 'EEW' :
                    eew_topic = result['topic']
                    mqtthost = "tcp://"+result['mqtthost']
                    port = result['port']
                    if "" == scopeLast :
                        scopeLast = result['scope']
                    else:
                        scopeLast = scopeLast+","+result['scope']
                if result['scope'] == 'EQR' :
                    eqr_topic = result['topic']
                    mqtthost = "tcp://"+result['mqtthost']
                    port = result['port']
                    if "" == scopeLast :
                        scopeLast = result['scope']
                    else:
                        scopeLast = scopeLast+","+result['scope']
                if result['scope'] == 'ACK' :
                    ack_topic = result['topic']
                    mqtthost = "tcp://"+result['mqtthost']
                    port = result['port']
                    if "" == scopeLast :
                        scopeLast = result['scope']
                    else:
                        scopeLast = scopeLast+","+result['scope']
        print("POST 请求返回的数据：")
        print(data)
    else:
        print(f"POST 请求失败，状态码：{response.status_code}")
    return eew_topic, eqr_topic, ack_topic, mqtthost,port,scopeLast

# 发送 POST 请求
url_post = "http://192.168.0.41:8098/client"

# 注册
def register(license):
    data_post = {
        'license': license,
        'owner': 'KX',
        'type': 'TER'
    }
    response_post = httpx.post(url_post+'/register/tm_register', data=data_post)
    return handle_post_response_register(response_post)
#授权
def authorize(clientId, uname, pwd):
    data_post = {
        'scope': 'EEW,EQR,ACK',
        'clientId': clientId,
        'uname': uname,
        'pwd' : pwd
    }
    response_post = httpx.post(url_post+'/register/tm_authorize', data=data_post)
    return handle_post_response_authorize(response_post)
